package org.dk.controller;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.dk.domain.DataResult;
import org.dk.em.DataResultEnum;
import org.dk.pojo.TbUser;
import org.dk.service.UserService;
import org.dk.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Objects;

@Controller
@RequestMapping("userController")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private UserService userService;

    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String emailFrom;

    public String getEmailFrom() {
        return emailFrom;
    }
    public void setEmailFrom(String emailFrom) {
        this.emailFrom = emailFrom;
    }

    @RequestMapping("toShow")
    public String ToShow(){

        return "register";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
           return "login";
      }

    @RequestMapping("register")
    @ResponseBody
    public DataResult register(TbUser user, String phoneCode){
        //redis中拿到验证码
        String o = (String) redisTemplate.opsForValue().get(user.getPhone());
        if(!Objects.equals(phoneCode,o)){
            return DataResult.buildDataResult(DataResultEnum.SUCCESS).setData("验证码错误");
        }
        TbUser us = userService.selectByName(user.getUsername());
        if(us != null){
            return DataResult.buildDataResult(DataResultEnum.SUCCESS).setData("该账号已存在");
        }
        String s = ShiroUtils.generateSalt(6);//生成
        String md5 = ShiroUtils.encryptPassword("MD5", user.getPassword(), s, 3);//加密
        user.setPassword(md5);
        user.setSalt(s);
        user.setCreated(new Date());
        user.setUpdated(new Date());
        userService.insertUser(user);
        return DataResult.buildDataResult(DataResultEnum.SUCCESS);
    }

    @ResponseBody
    @RequestMapping("login")
    public DataResult Login(TbUser user){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        try {
            subject.login(token);
        }catch (UnknownAccountException | IncorrectCredentialsException e){
            return DataResult.buildDataResult(DataResultEnum.ERROR).setData("账号或密码错误");
        }

        return DataResult.buildDataResult(DataResultEnum.SUCCESS);
    }

    @RequestMapping("updatepwd")
    public String  updatepwd(){

        return "updatepwd";
    }

    @RequestMapping("getPassWord")
    @ResponseBody
    public DataResult getPassWord(String email,String phone,String password){
        //根据邮箱手机号查出用户
        TbUser user =userService.getPassWord(email,phone);
        //重新设定密码,用shiro,
        String md5 = ShiroUtils.encryptPassword("MD5", password, user.getSalt(), 3);
        user.setPassword(md5);
        userService.updateUser(user);
        String subject = "测试普通邮件,您的密码为:"+password;
        String content = "测试普通邮件,邮件为系统发送，请勿回复！";
        String[] toArr = {"3428299089@qq.com", "2628876073@qq.com"};
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(emailFrom);
            helper.setTo(toArr);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
